<template>
    <!-- 头部 -->
    <div class="dept_container">


        <!-- 查询条件 -->
        <div class="dept_where">
            <el-form :inline="true" label-position="left" class="form-inline">
                <el-form-item label="库位编码：">
                    <el-input v-model="location_code" style="width: 200px;" />
                </el-form-item>
                <el-form-item label="库位名称：">
                    <el-input v-model="zone_name" style="width: 200px;" />
                </el-form-item>
                <el-button type="primary" @click="queryDept()">查询</el-button>
                <el-button @click="reset">重置</el-button>
                <el-button type="success" @click="addlocation()">新增</el-button>
                <el-button @click="fhlocation()">返回</el-button>
            </el-form>
        </div>

        <!-- 按钮组 -->
        <div class="button-group">
            <span>库位位置：</span>
            <el-input-number v-model="location_x_position" :min="0" />
            <el-input-number v-model="location_y_position" :min="0" />
            <el-input-number v-model="location_z_position" :min="0" />
        </div>
    </div>


    <el-table :data="tableData" :header-cell-style="{
    textAlign: 'center',
    background: '#f5f7fa',
    fontWeight: 'bold',
    position: 'sticky',
    top: 0,

}" :cell-style="{ textAlign: 'center', }" style="width: 100%; position: relative;
        top: -90px;" border>

        <el-table-column prop="location_code" label="库位编码" show-overflow-tooltip fixed width="100%">
            <template #default="scope">
                <span style="cursor: pointer; color: #409EFF;" @click="detail(scope.row)">
                    {{ scope.row.location_code }}
                </span>
            </template>
        </el-table-column>
        <el-table-column prop="location_name" label="库位名称" show-overflow-tooltip width="100%">
        </el-table-column>
        <el-table-column prop="location_max_capacity" label="最大容量" show-overflow-tooltip width="100%">
        </el-table-column>
        <el-table-column prop="location_available_capacity" label="可用容量" show-overflow-tooltip width="100%">
        </el-table-column>
        <el-table-column prop="location_used_capacity" label="已用容量" show-overflow-tooltip width="100%">
        </el-table-column>
        <el-table-column prop="location_x_position" label="库位位置X" show-overflow-tooltip width="90">
        </el-table-column>
        <el-table-column prop="location_y_position" label="库位位置Y" show-overflow-tooltip width="90">
        </el-table-column>
        <el-table-column prop="location_z_position" label="库位位置Z" show-overflow-tooltip width="90">
        </el-table-column>

        <el-table-column prop="location_allow_mix" label="允许产品混放" show-overflow-tooltip>
            <template #default="scope">
                <el-tag :type="scope.row.location_allow_mix ? 'success' : 'info'"
                    :style="{ color: scope.row.location_enable === '1' ? 'blue' : '' }">
                    {{ scope.row.location_allow_mix==='1' ? '是' : '否' }}
                </el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="location_batch_mix" label="允许批次混放" show-overflow-tooltip>
            <template #default="scope">
                <el-tag :type="scope.row.location_batch_mix ? 'success' : 'info'"
                    :style="{ color: scope.row.location_batch_mix === '1' ? 'blue' : '' }">
                    {{ scope.row.location_batch_mix === '1' ? '是' : '否' }}
                </el-tag>
            </template>
        </el-table-column>


        <el-table-column prop="location_enable" label="是否启用" show-overflow-tooltip>
            <template #default="scope">
                <el-tag :type="scope.row.location_enable ? 'success' : 'info'"
                    :style="{ color: scope.row.location_enable === '1' ? 'blue' : '' }">
                    {{ scope.row.location_enable === '1' ? '是' : '否' }}
                </el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="location_freeze" label="是否冻结" show-overflow-tooltip width="170" align="center">
            <template #default="scope">
                <div class="switch-wrapper">
                    <!-- 状态标签 -->
                    <span class="status-label">
                        {{ scope.row.location_freeze === "1" ? '是（已冻结）' : '否（未冻结）' }}
                    </span>

                    <!-- 可点击的开关 -->
                    <div class="switch-display" :class="{ 'switch-on': Number(scope.row.location_freeze) === 1 }"
                        role="switch" :aria-checked="scope.row.location_freeze === '1'" @click="toggleFreeze(scope.row)"
                        tabindex="0" aria-label="点击切换冻结状态">
                        <span class="slider"></span>
                    </div>
                </div>
            </template>
        </el-table-column>


        <el-table-column prop="remarks" label="备注" show-overflow-tooltip width="200" align="center">
        </el-table-column>

        <el-table-column label="操作" width="200" show-overflow-tooltip fixed="right">
            <template #default="scope">
                <div class="action-buttons">

                    <el-button size="small" @click="warehouseLocationupdate(scope.row)">修改</el-button>
                    <el-button type="danger" size="small" @click="warehouseDelete(scope.row)">删除</el-button>
                </div>
            </template>
        </el-table-column>

    </el-table>
    <!-- 分页 -->
    <div class="block">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[5, 10, 20, 30]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="pageCount">
        </el-pagination>
    </div>

    <!--右边侧边栏-->
    <el-drawer v-model="dialogVisible" :title="title" :direction="direction" :before-close="handleClose" size="30%"
        :show-close="false" @close="close">
        <div style="display: flex; justify-content: center; height: 100%;">

            <el-form name="configfilefirstkindForm" method="post" ref="ruleFormRef" :model="Warehousearealocation"
                :rules="rules" style="width: 80%; margin-top: 20px;">

                <el-form-item prop="location_code" label="库位编码" style="justify-content: center;">
                    <div style="display: flex; align-items: center; gap: 10px;">
                        <!-- 输入框禁用 -->
                        <el-input v-model="Warehousearealocation.location_code" placeholder="仓库编码" clearable
                            style="width: 50%;"
                            :disabled="Warehousearealocation.auto_generate_code === '1' || Warehousearealocation.isEditMode" />

                        <!-- 开关禁用 -->
                        <el-switch v-model="Warehousearealocation.auto_generate_code" :active-value="'1'"
                            :inactive-value="'0'" @change="handleAutoGenerateCodeChange" active-color="#13ce66"
                            inactive-color="#ff4949" :disabled="Warehousearealocation.isEditMode" />
                        <span style="color: blue;"> 自动生成 </span>
                    </div>
                </el-form-item>

                <el-form-item prop="location_name" label="库位名称" style="justify-content: center;">
                    <el-input v-model="Warehousearealocation.location_name" placeholder="库区名称" clearable
                        style="width: 100%;" />
                </el-form-item>

                <el-form-item label="库位容量" prop="location_max_capacity" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_max_capacity" :min="0"
                        @change="handleCapacityChange" />
                </el-form-item>


                <el-form-item label="可用容量" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_available_capacity" :min="0"
                        :disabled="isDisabled" @change="changeCapacity_available" />
                </el-form-item>

                <el-form-item label="已用容量" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_used_capacity" :min="0"
                        :disabled="IsDisWeahouse_location_used" />
                </el-form-item>



                <el-form-item label="是否冻结" style="display: flex; justify-content: center; ">
                    <el-radio-group v-model="Warehousearealocation.location_freeze">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>



                <el-form-item label="是否启用" style="display: flex; justify-content: center; margin-left: 0px;">
                    <el-radio-group v-model="Warehousearealocation.location_enable">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="产品混放" style="display: flex; justify-content: center; margin-left: 0px;">
                    <el-radio-group v-model="Warehousearealocation.location_allow_mix">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="批次混放" style="display: flex; justify-content: center; margin-left: 0px;">
                    <el-radio-group v-model="Warehousearealocation.location_batch_mix">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>
                </el-form-item>

                <el-form-item label="库位位置X" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_x_position" :min="0" :max="999" />
                </el-form-item>

                <el-form-item label="库位位置Y" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_y_position" :min="0" :max="999" />
                </el-form-item>

                <el-form-item label="库位位置Z" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_z_position" :min="0" :max="999" />
                </el-form-item>



                <el-form-item label="备注信息" style="justify-content: center;">
                    <el-input type="textarea" :rows="2" v-model="Warehousearealocation.remarks" placeholder="备注"
                        clearable style="width: 100%;" />
                </el-form-item>

            </el-form>
        </div>

        <template #footer>
            <div class="dialog-footer" style="text-align: center;">
                <el-button @click="close">取消</el-button>
                <el-button type="primary" @click="Warehouse_locationInfoAdd">确定</el-button>
            </div>
        </template>
    </el-drawer>

    <!--模态框-->
    <el-dialog title="查看库位" width="30%" v-model="dialogVisibleSwer">


        <div style="display: flex; justify-content: center; height: 100%;">

            <el-form name="configfilefirstkindForm" method="post" ref="ruleFormRef" :model="Warehousearealocation"
                :disabled="true" style="width: 80%; margin-top: 20px;">

                <el-form-item prop="location_code" label="库位编码" style="justify-content: center;">
                    <el-input v-model="Warehousearealocation.location_code" placeholder="仓库编码" clearable
                        style="width: 50%;" />
                </el-form-item>

                <el-form-item prop="location_name" label="库位名称" style="justify-content: center;">
                    <el-input v-model="Warehousearealocation.location_name" placeholder="库区名称" clearable
                        style="width: 50%;" />
                </el-form-item>

                <el-form-item label="库位容量" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_max_capacity" :min="0"
                        @change="handleCapacityChange" />
                </el-form-item>


                <el-form-item label="可用容量" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_available_capacity" :min="0"
                        :disabled="isDisabled" @change="changeCapacity_available" />
                </el-form-item>

                <el-form-item label="已用容量" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_used_capacity" :min="0"
                        :disabled="IsDisWeahouse_location_used" />
                </el-form-item>



                <el-form-item label="是否冻结" style="display: flex; justify-content: center;">
                    <el-radio-group v-model="Warehousearealocation.location_freeze">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>

                    <el-form-item label="是否启用" class="enable-radio">
                        <el-radio-group v-model="Warehousearealocation.location_enable">
                            <el-radio value="1">是</el-radio>
                            <el-radio value="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form-item>


                <el-form-item label="产品混放" style="display: flex; justify-content: center;">
                    <el-radio-group v-model="Warehousearealocation.location_allow_mix">
                        <el-radio value="1">是</el-radio>
                        <el-radio value="0">否</el-radio>
                    </el-radio-group>

                    <el-form-item label="批次混放" class="enable-radio">
                        <el-radio-group v-model="Warehousearealocation.location_batch_mix">
                            <el-radio value="1">是</el-radio>
                            <el-radio value="0">否</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </el-form-item>

                <el-form-item label="库位位置X" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_x_position" :min="0" />
                </el-form-item>

                <el-form-item label="库位位置Y" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_y_position" :min="0" />
                </el-form-item>

                <el-form-item label="库位位置Z" style="justify-content: center;">
                    <el-input-number v-model="Warehousearealocation.location_z_position" :min="0" />
                </el-form-item>



                <el-form-item label="备注信息" style="justify-content: center;">
                    <el-input type="textarea" :rows="2" v-model="Warehousearealocation.remarks" placeholder="备注"
                        clearable style="width: 100%;" />
                </el-form-item>

            </el-form>
        </div>
        <span class="dialog-footer">
            <el-button @click="gbmtk">取消</el-button>
            <el-button type="primary" @click="confirmLoss">返回</el-button>
        </span>
    </el-dialog>

</template>

<script setup>
import { ref, onMounted, reactive } from 'vue'
import axios from 'axios';
import { useWarehouseStore } from '@/storejs/warehouseStore'
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
//页面跳转获取数据
const warehouseStore = useWarehouseStore()
const warehouse_codego = ref(warehouseStore.zone_code) 


const tableData = ref([]);// 表格数据对象



var location_code = ref('')

var zone_name = ref('')

const currentPage = ref(1)//当前页

const pageSize = ref(5)//每页显示数

const pageCount = ref(0)//总记录数

var location_x_position=ref(0);//库位位置X

var location_y_position = ref(0);//库位位置y

var location_z_position = ref(0);//库位位置z
//编码验证
const ruleFormRef = ref();

const dialogVisible = ref(false)//右边侧边栏显示

const title = ref("添加库区信息")

//控制 Element Plus 的抽屉Drawer组件从哪个方向滑出。
const direction = ref('rtl')
//控制已用容量
const isDisabled = ref(true);

const IsDisWeahouse_location_used=ref(true);

    // 禁用库存容量的变量触发器
const enableChangeEvent = ref(true);

//判断是添加还是修改的变量
var location_id=ref(0);





//模态框的显示
const dialogVisibleSwer = ref(false);

//初始化数据对象
let location={
    zone_code: warehouse_codego.value,//库区编码
    location_code:"",//库位编码
    location_name:"",//库位名称
    location_max_capacity:0,//最大容量
    location_available_capacity:0, //可用容量
    location_used_capacity:0,//已用容量
    location_x_position:0,//库位位置X
    location_y_position:0,//库位位置y
    location_z_position:0,//库位位置z
    location_allow_mix:0,//允许产品混放
    location_batch_mix:0,//允许批次混放
    location_enable:'1',//启用状态
    location_freeze:'0',//冻结状态
    remarks:"",//备注信息
    Create_by: localStorage.getItem('userLName'),
    Create_time: dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ'),
    update_by: "",//修改人
    Update_time: "",
    Del_flag: '0',
    auto_generate_code: '0',//是否自动生成库位编码
    isEditMode: false,//是否是编辑模式
}

//模态对象
const Warehousearealocation = reactive({ ...location })

//插件路由器实例
var router = useRouter();

//返回
function fhlocation(){
    router.push('/main/DB/WarehouseareaInfo');

}

// 表单验证规则（示例）
const rules = reactive({
    location_code: [
        { required: true, message: '库区编码不能为空', trigger: 'blur' }
    ],
    location_name: [
        { required: true, message: '库区名称不能为空', trigger: 'blur' }
    ],
    location_allow_mix:[
        { required: true, message: '请选择是否允许产品混放', trigger: 'change' }
    ],
    location_batch_mix:[
        { required: true, message: '请选择是否允许批次混放', trigger: 'change' }
    ]
})

//判断库位编码是否存在
async function WarehouseLocation_code_judgment() {

    try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_location/WarehouseLocation_code_judgment", {
            params: {
                location_code: Warehousearealocation.location_code,
                zone_code: warehouse_codego.value
            },
            authorization: `Bearer ${localStorage.getItem('token')}`,
        });

        if (res.data > 0) {
            ElMessage.error('仓库编码已存在');

            return false;
        }
        console.log('请求成功:', res.data);
        return true;

    } catch (err) {
        console.error('请求失败:', err);
        return false;
    }
}


function warehouseDelete(row) {
    ElMessageBox.confirm(
        `你确定要删除编号为 ${row.location_code} 的库位吗？`,
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            axios.put(
                "http://localhost:5181/api/Db_warehouse_location/warehouselocation_tombstone",
                {}, // put 请求如果没有 body 数据可以传空对象
                {
                    params: {
                        zone_code: row.zone_code,
                        location_code: row.location_code
                    },
                    headers: {
                        Authorization: localStorage.getItem("token")
                    }
                }
            )
                .then((result) => {
                    if (result.data > 0) {
                        ElMessage.success(`仓库${row.location_name}删除成功`)
                        Count();
                        fill();
                    } else {
                        ElMessage.success(`库位${row.location_name}中还有库存不可以删除`)
                    }

                })
                .catch((err) => {
                    console.error(err);
                });
        })
  
}


//判断库位名称是否存在
async function Warehouselocation_name_judgment() {

    try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_location/WarehouseLocation_name_judgment", {
            params: {
                location_name: Warehousearealocation.location_name,
                zone_code: warehouse_codego.value
            },
            authorization: `Bearer ${localStorage.getItem('token')}`,
        });

        if (res.data > 0) {
            ElMessage.error('库位名称已存在');

            return false;
        }
        return true;

    } catch (err) {
        console.error('请求失败:', err);
        return false;
    }
}


//判断库位名称修改是否存在
async function Warehousezone_name1_judgment11() {

    try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_location/WarehouseLocation_name_judgment", {
            params: {
                location_name: Warehousearealocation.location_name,
                zone_code: warehouse_codego.value
            },
            authorization: `Bearer ${localStorage.getItem('token')}`,
        });

        if (res.data > 2) {
            ElMessage.error('库位名称已存在');

            return false;
        }
        return true;

    } catch (err) {
        console.error('请求失败:', err);
        return false;
    }
}


// 触发器库位容量 -- 当最大容量变化时触发
const handleCapacityChange = (val) => {
    
    if (enableChangeEvent.value) {
      
        changeCapacity(val);
    }
    const available = Warehousearealocation.location_available_capacity;

  

    if (available >= val) {
        isDisabled.value = true;

        // 自动修正可用容量
        Warehousearealocation.location_available_capacity = val;

     
    } else {
        isDisabled.value = false;
    }

    Calculate_theused_capacity();
  
}

// 可用容量改变时触发
const changeCapacity = (val) => {
    Warehousearealocation.location_available_capacity = val;
}


const changeCapacity_available=(val)=>{
    if (val>=Warehousearealocation.location_max_capacity){
        isDisabled.value = true;
    }
    Calculate_theused_capacity();
}

//计算已用容量
function Calculate_theused_capacity(){
    Warehousearealocation.location_used_capacity=Warehousearealocation.location_max_capacity-Warehousearealocation.location_available_capacity;
}

//点击添加
function addlocation(){
    location_id = 0;
    //清空数据
    Object.assign(Warehousearealocation, location)
    dialogVisible.value = ref(true)
    // 添加模式下允许 change 事件触发
    enableChangeEvent.value = true;

    // 添加模式下禁用可用容量输入框
    isDisabled.value = true;
   
}

//模态取消
function gbmtk(){
    dialogVisibleSwer.value = false;
    //清空数据
    Object.assign(Warehousearealocation, location)
}

function confirmLoss(){
    dialogVisibleSwer.value = false;
    //清空数据
    Object.assign(Warehousearealocation, location)

}


//点击修改
function warehouseLocationupdate(row){
    location_id = 1;
   
    enableChangeEvent.value = false;

    title.value = "修改库位设置"

    //显示侧边栏
    dialogVisible.value = ref(true)

    //不可以进行修改库区编码
    Warehousearealocation.isEditMode = true;

    //修改数据--一键赋值
    Object.assign(Warehousearealocation, row)
    Warehousearealocation.update_by = localStorage.getItem('userLName')
    Warehousearealocation.Update_time = dayjs().format('YYYY-MM-DDTHH:mm:ss.SSSZ')


    
    isDisabled.value = false

    if (Warehousearealocation.location_available_capacity >= Warehousearealocation.location_max_capacity) {
        //将库区可用容量禁用
        isDisabled.value = true;
    }
}


//添加的时候判断库位的容量不可以超过库区容量
async function Warehouselocation_Capacity_judgment() {
    try {
        const res = await axios.get("http://localhost:5181/api/Db_warehouse_location/Warehouselocation_Capacity_judgment", {
            params: {
                zone_code: Warehousearealocation.zone_code,
                location_max_capacity: Warehousearealocation.location_max_capacity
            },
            headers: { Authorization: localStorage.getItem("token") }
        });

        if (res.data > 0) {
            return true; // ✅ 合法
        } else {
            ElMessage.error('库位容量不可以大于库区容量');

            return false; // ❌ 不合法
        }
    } catch (err) {
        console.error('请求失败:', err);
        return false;
    }
}


//修改判名称
async function Warehouse_Location_name_Judgment_update() {
  try {
      const res = await axios.get("http://localhost:5181/api/Db_warehouse_location/Warehouse_Location_name_UpdateJudgment", {
      params: {
            location_name: Warehousearealocation.location_name,
            zone_code: warehouse_codego.value,
            location_code: Warehousearealocation.location_code
      },
      headers: {
        authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (res.data > 0) {
      ElMessage.error('库位名称已存在');
      return false;
    }
    return true;
  } catch (err) {
    console.error('请求失败:', err);
    return false;
  }
}

//修改容量判断
async function Warehouselocation_Capacity_Judgment_update() {
  try {
      const res = await axios.get("http://localhost:5181/api/Db_warehouse_location/Warehouselocation_Capacity_UpdateJudgment", {
      params: {
        zone_code: warehouse_codego.value,
              location_code: Warehousearealocation.location_code,
              new_location_max_capacity: Warehousearealocation.location_max_capacity
      },
      headers: {
        authorization: `Bearer ${localStorage.getItem('token')}`
      }
    });

    if (res.data === 0) {
      ElMessage.error('库位容量超过库区最大容量');
      return false;
    } else if (res.data === -1) {
      ElMessage.error('库区不存在或已删除');
      return false;
    }
    return true;
  } catch (err) {
    console.error('请求失败:', err);
    return false;
  }
}

//添加和修改
async function Warehouse_locationInfoAdd(){
   
    if (location_id ==0){
       
        //添加
        ruleFormRef.value.validate(async (valid) => {
            if (valid) {
                const isCodeValid = WarehouseLocation_code_judgment();   // 启动第一个检查
                const isNameValid = Warehouselocation_name_judgment();  // 启动第二个检查
                const isCapacityValid = Warehouselocation_Capacity_judgment();

                const [isCodeValidSwer, isNameValidSwer, isCapacityValidSwer] = await Promise.all([isCodeValid, isNameValid, isCapacityValid]);
             
                if(!isCodeValidSwer || !isNameValidSwer || !isCapacityValidSwer){
                    console.log('库区编码或名称重复，无法提交');
                    return;
                }
                //console.log(Warehousearealocation)
                axios.put("http://localhost:5181/api/Db_warehouse_location/warehouse_location_Insert", Warehousearealocation,{
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`,
                    }
                }).then((res)=>{
                    if(res.data>0){
                        //提示
                        ElMessage.success('添加成功')
                        //关闭右边侧边栏
                        dialogVisible.value = false;
                        //清空数据
                        Object.assign(Warehousearealocation, location)
                        //统计方法
                        Count();
                        //重新查询
                        fill();
                        
                    }else{
                        ElMessage.error('添加失败')
                    }
                }).catch((err)=>{
                    console.log(err)
                })
            }   
          
            
        })
    }else{
      

        const isCodeValid = Warehouse_Location_name_Judgment_update();   // 启动第一个检查
        const isCapacityValid = Warehouselocation_Capacity_Judgment_update(); // 启动第三个检查

        const [isCodeValidSwer, isCapacityValidSwer] = await Promise.all([isCodeValid, isCapacityValid]);

        if (!isCodeValidSwer || !isCapacityValidSwer) {

            return;
        }
        //修改
        axios.put("http://localhost:5181/api/Db_warehouse_location/warehouse_locationUpdate", Warehousearealocation, {
            headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`,
            }
        }).then((res) => {
            if (res.data >= 0) {
                ElMessage.success('修改成功');
                //关闭弹窗
                dialogVisible.value = false;
                //清空数据
                Object.assign(Warehousearealocation, location)
                //刷新数据
                Count();
                fill()
            }
        }).catch((err) => {
            console.log(err)
        })
    }
  
}

//取消
function close() {
    dialogVisible.value = false;
    //清空数据
    Object.assign(Warehousearealocation, location)
}


//点击切换冻结状态
function toggleFreeze(row) {
    if(row.location_freeze==0){
        ElMessageBox.confirm(
            `你确定要冻结${row.location_name}`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            axios.put("http://localhost:5181/api/Db_warehouse_location/warehouselocationFrozenstate", {},
                {
                    params: {
                        id: row.location_id,
                        location_freeze: row.location_freeze
                    },
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`,
                    }
                }
            ).then((res => {
                ElMessage.success('冻结成功')
                fill()
            })
            ).catch((err) => {
                console.log(err)
            })
        }).catch(() => {
            console.log('取消')
        })
    }else{
        ElMessageBox.confirm(
            `你确定要解冻${row.location_name}`,
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        ).then(() => {
            axios.put("http://localhost:5181/api/Db_warehouse_location/warehouselocationFrozenstate", {},
                {
                    params: {
                        id: row.location_id,
                        location_freeze: row.location_freeze
                    },
                    headers: {
                        authorization: `Bearer ${localStorage.getItem('token')}`,
                    }
                }
            ).then((res => {
                ElMessage.success('解冻成功')
                fill()
            })
            ).catch((err) => {
                console.log(err)
            })
        }).catch(() => {
            console.log('取消')
        }) 
    }
   
}




//编码自动生成
function handleAutoGenerateCodeChange(value) {
    if (value === '1') {
        // 开启自动生码
        axios.get("http://localhost:5181/api/DJBH/DJBH", {
            params: {
                en_code: 5
            }, headers: {
                authorization: `Bearer ${localStorage.getItem('token')}`,
            }
        }).then((res) => {
            console.log(res.data);
            Warehousearealocation.location_code = res.data;
            // 手动触发验证
            ruleFormRef.value.validateField('zone_code', (valid) => {
                if (valid) {
                    console.log('验证通过');
                } else {
                    console.log('验证失败');
                }
            });
        }).catch((err) => {
            console.log(err);
        })
    } else {
        // 关闭自动生码，清空编码
        Warehousearealocation.zone_code = '';
    }
}


// 每页数量变化--选择传递每页显示数
const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    //重新按照pageSize和currentPage重新请求数据
    fill();
};

// 当前页变化
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    //重新按照pageSize和currentPage重新请求数据
    fill();
};

//点击编码显示模态框,查看详细信息
function detail(row){
    dialogVisibleSwer.value = true;
    //修改数据--一键赋值
    Object.assign(Warehousearealocation, row)
} 



//点击查询
function queryDept(){

fill();
Count();
}
//点击重置
function reset(){
    location_code.value = '';
    zone_name.value = '';
    location_x_position.value = 0;
    location_y_position.value = 0;
    location_z_position.value = 0;
    //重新调用查询
    fill();
}


//分页方法
function fill() {
    axios.get("http://localhost:5181/api/Db_warehouse_location/Warehouse_locationfY", {
        params: {
            zone_code: warehouse_codego.value,
            location_code: location_code.value, 
            warehouse_name: zone_name.value,
            location_x_position: location_x_position.value,
            location_y_position: location_y_position.value,
            location_z_position: location_z_position.value,
            currentPage: currentPage.value,
            pageSize: pageSize.value
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`,
        }
    }).then((result) => {
        tableData.value = result.data;
    
    }).catch((err) => {
        console.info(err)
    })
}

//查询总数
function Count() {
    axios.get("http://localhost:5181/api/Db_warehouse_location/Warehouse_locationCount", {
        params: {
            zone_code: warehouse_codego.value,
            warehouse_name: zone_name.value,
            location_x_position: location_x_position.value,
            location_y_position: location_y_position.value,
            location_z_position: location_z_position.value,
         
        },
        headers: {
            authorization: `Bearer ${localStorage.getItem('token')}`,
        }
    }).then((result) => {
        pageCount.value = result.data

    }).catch((err) => {
        console.info(err)
    })
}
onMounted(() => {
    fill();
    Count();
})
</script>



<style scoped>
  .block {
      display: flex;
      justify-content: center;
position: relative;
    top: -90px;
      margin-top: 20px;
  }
.enable-radio {
    margin-left: 20px;
    
}

        :deep(.el-radio) {
            display: inline-flex;
            align-items: center;
        }
    
        /* 选中状态的样式 */
        :deep(.el-radio__input.is-checked + .el-radio__label) {
            color: #409eff;
            font-weight: bold;
        }
    
        :deep(.el-radio__input.is-checked .el-radio__inner) {
            background-color: #409eff;
            border-color: #409eff;
        }

    .dept_container {
        padding: 20px;
        
    }

    .dept_title {
        font-size: 20px;
        font-weight: bold;
        margin-bottom: 20px;
        
    }

    .dept_where {
        display: flex;
        align-items: center;
        gap: 20px;
        margin-bottom: 20px;
        margin-top: 30px;
        position: relative;
        top: -90px;
       
    }

    .dept_where .el-form-item {
        margin-bottom: 0;
        
    }

    .form-inline {
        display: flex;
        flex-wrap: wrap;
        gap: 15px;
        align-items: center;
        
    }

    .button-group {
        display: flex;
        align-items: center;
        gap: 10px;
        margin-top: 15px;
        font-size: 14px;
        position: relative;
        top: -90px;
    }

    .button-group span {
        white-space: nowrap;
        margin-right: 10px;
        
    }

    .el-button+.el-button {
        margin-left: 10px;
        
    }

    .action-buttons {
        display: flex;
        flex-wrap: wrap;
        gap: 8px;
        /* 按钮间距 */
    }

    /* 响应式调整 */
    @media (max-width: 1600px) {
        .action-buttons {
            gap: 4px;
        }

        .action-buttons .el-button {
            padding: 6px 8px;
            font-size: 12px;
        }
    }

    .el-button--primary {
        position: relative;

    }

    .button-group {
        display: flex;
        margin: 8px;
        
    }

    .dept_title {
        float: left;
        font-weight: bold;
        margin-top: -10px;
        font-size: 20px;
        
    }

    .dept_where {
        display: left;
        margin-left: 10px;
        margin-top: 40px;
        
    }

    .dept_input {
        margin-right: 20px;
        
    }

    .switch-wrapper {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 12px;
        
    }

    .status-label {
        font-weight: 500;
        min-width: 90px;
        text-align: center;
        font-size: 13px;
        color: #333;
    }

    /* 开关容器 */
    .switch-display {
        position: relative;
        width: 50px;
        height: 24px;
        border-radius: 12px;
        background-color: #dcdfe6;
        /* 默认灰色背景 */
        cursor: pointer;
        user-select: none;
        transition: background-color 0.3s ease;
    }

    /* 开启状态样式 */
    .switch-display.switch-on {
        background-color: #409eff;
        /* 正常蓝色表示开启 */
    }

    /* 滑块样式 */
    .slider {
        position: absolute;
        width: 22px;
        height: 22px;
        border-radius: 50%;
        background-color: white;
        top: 1px;
        transition: left 0.3s ease;
    }



    /* 关闭状态滑块位置 */
    .switch-display .slider {
        left: 1px;
    }

    /* 开启状态滑块位置 */
    .switch-display.switch-on .slider {
        left: calc(100% - 23px);
        /* 让滑块移动到右边 */
    }
    /*模态图片框 */
     

</style>